package dao

import (
	"gorm.io/gorm"
	"kf/models/entity"
	"strconv"
)

type SysUserRolesDao struct {
	DB *gorm.DB
}

func (sysUserRolesDao *SysUserRolesDao) FindRoleByUserId(userId interface{}) entity.SysUserRole {
	var uRole entity.SysUserRole
	sysUserRolesDao.DB.Where("user_id = ?", userId).First(&uRole)
	return uRole
}

func (sysUserRolesDao *SysUserRolesDao) FindRolesByUserId(userId uint64) []entity.SysUserRole {
	var userRoles []entity.SysUserRole
	sysUserRolesDao.DB.Where("user_id = ?", userId).Find(&userRoles)
	return userRoles
}

// 保存用户角色
func (sysUserRolesDao *SysUserRolesDao) saveUserRoles(userId uint64, roleIds []uint64) {
	//先删除已有数据
	err := sysUserRolesDao.DB.Delete(&entity.SysUserRole{}, "user_id = ?", userId).Error
	if err != nil {
		panic(err)
	}

	//再保存新数据
	var userRoles []entity.SysUserRole
	for _, roleId := range roleIds {
		uRole := entity.SysUserRole{
			UserId: strconv.Itoa(int(userId)),
			RoleId: roleId,
		}
		userRoles = append(userRoles, uRole)
	}
	sysUserRolesDao.DB.CreateInBatches(&userRoles, 10)
}

// 创建用户角色
func (sysUserRolesDao *SysUserRolesDao) CreateUserRole(userId uint, roleId uint) {
	uRole := &entity.SysUserRole{
		UserId: strconv.Itoa(int(userId)),
		RoleId: uint64(roleId),
	}
	sysUserRolesDao.DB.Create(uRole)
}
func (sysUserRolesDao *SysUserRolesDao) DeleteRoleByUserId(userId interface{}) {
	sysUserRolesDao.DB.Where("user_id = ?", userId).Delete(entity.SysUserRole{})
}

// 查找对应的角色id是否被应用
func (sysUserRolesDao *SysUserRolesDao) HasAssignedUsers(roleId uint64) (bool, error) {
	var count int64
	sql := `SELECT
            count(*)
        FROM
            sys_user_role t1
            INNER JOIN sys_role t2 ON t1.role_id = t2.id AND t2.is_deleted = 0
            INNER JOIN sys_user t3 ON t1.user_id = t3.id
            AND t3.is_deleted = 0
        WHERE
            t1.role_id = ?`
	err := sysUserRolesDao.DB.Raw(sql, roleId).Count(&count).Error
	if err != nil {
		return false, err
	}
	return count > 0, nil
}
